package com.himiotech.core.framework.config.shiro.service;

import cn.hutool.core.util.StrUtil;
import com.himiotech.core.framework.config.async.AsyncFactory;
import com.himiotech.core.framework.config.async.AsyncManager;
import com.himiotech.core.framework.helper.constant.ShiroConstants;
import com.himiotech.core.framework.helper.constant.UserConstants;
import com.himiotech.core.framework.helper.exception.user.UserNotExistsException;
import com.himiotech.core.framework.helper.exception.user.UserPasswordRetryLimitExceedException;
import com.himiotech.core.framework.helper.service.ConfigService;
import com.himiotech.core.project.model.entity.user.User;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 登录密码方法
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Service
public class PasswordService {
    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private ConfigService configService;

    private Cache<String, AtomicInteger> loginRecordCache;

    @PostConstruct
    public void init() {
        loginRecordCache = cacheManager.getCache(ShiroConstants.LOGINRECORDCACHE);
    }

    public void validate(User user, String password) {
        String loginName = user.getLoginName();

        AtomicInteger retryCount = loginRecordCache.get(loginName);

        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            loginRecordCache.put(loginName, retryCount);
        }
        String maxRetryCount = configService.getKey("sys.password.maxRetryCount");
        if (retryCount.incrementAndGet() > Integer.parseInt(maxRetryCount)) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(loginName, UserConstants.LOGIN_FAIL, StrUtil.format("密码输入错误{}次，帐户锁定10分钟", maxRetryCount)));
            throw new UserPasswordRetryLimitExceedException(Integer.parseInt(maxRetryCount));
        }

        if (!matches(user, password)) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(loginName, UserConstants.LOGIN_FAIL, StrUtil.format("密码输入错误{}次", retryCount)));
            loginRecordCache.put(loginName, retryCount);
            throw new UserNotExistsException();
        } else {
            clearLoginRecordCache(loginName);
        }
    }

    public boolean matches(User user, String newPassword) {
        return user.getPassword().equals(encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
    }

    public void clearLoginRecordCache(String loginName) {
        loginRecordCache.remove(loginName);
    }

    public String encryptPassword(String loginName, String password, String salt) {
        return new Md5Hash(loginName + password + salt).toHex();
    }
}
